<?php
/*
/**
* CHRONOFORMS version 3.0 
* Copyright (c) 2008 Chrono_Man, ChronoEngine.com. All rights reserved.
* Author: Chrono_Man (ChronoEngine.com)
* @license		GNU/GPL
* See readme.html.
* Visit http://www.ChronoEngine.com for regular update and information.
**/
defined('_JEXEC') or die('Restricted access'); 

class CFCustomCode extends JObject{
	var $thisformid;
	function __construct($formid){		
		if (!isset($formid)) {
			JError::raiseWarning( '1001', 'LOADING FAILED::CustomCode Class' );
			$retval = false;
			return $retval;
		}
		else
		{
			//initialise
			$this->thisformid = $formid;
		}
	}
	function &getInstance($formid){
		static $instances;
		if (!isset ($instances)) {
			$instances = array (  );
		}
		if (empty($instances[$formid])) {
			$instances[$formid] = new CFCustomCode($formid);
		}
		return $instances[$formid];
	}
	function runCode( $type, $emailevent = '' )
	{
		global $mainframe;
		$database =& JFactory::getDBO();
		$posted = JRequest::get( 'post' , JREQUEST_ALLOWRAW );
		//form instance
		$formname = CFChronoForm::getFormName($this->thisformid);
		$MyForm =& CFChronoForm::getInstance($formname);
		//emails instance
		$MyFormEmails =& CFEMails::getInstance($MyForm->formrow->id);
		//run code
		if($type == 'onsubmitcode'){
			if ( !empty($MyForm->formrow->onsubmitcode) ) {
				ob_start();
				eval( "?>".$MyForm->formrow->onsubmitcode );
				$onsubmitcode = ob_get_clean();
				foreach ( $posted as $name => $post) {
					if(is_array($post)){
						$post = implode(", ", $post);
					}
					$onsubmitcode = str_replace("{".$name."}", $post, $onsubmitcode);
				}
				echo $onsubmitcode;
			}
		}
		if($type == 'onsubmitcodeb4'){
			if ( !empty($MyForm->formrow->onsubmitcodeb4) ){
				eval( "?>".$MyForm->formrow->onsubmitcodeb4 );
			}
		}
	
		if($type == 'autogenerated'){
			if($MyForm->formparams('savedataorder') == $emailevent){
				if ( !empty($MyForm->formrow->autogenerated) ) {
					eval( "?>".$MyForm->formrow->autogenerated );
				}
			}
		}
	}	
}